//
//  HMPicturePickerController.swift
//  Weibo
//
//  Created by ZhuDong on 16/5/30.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import HMImagePicker

let pictureCellID = "pictureCellID"
private let margin: CGFloat = 3
private let colCountKey = 4
private let cellWKey: CGFloat = (ScreenWidth - 5 * margin) / CGFloat(colCountKey)
private let maxImageCount = 3
class HMPicturePickerController: UICollectionViewController {
    var images: [UIImage] = [UIImage]()
    var imagesAsset:[PHAsset] = [PHAsset]()
    
    init(){
        let itemS = CGSize(width: cellWKey, height: cellWKey)
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = itemS
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        layout.sectionInset = UIEdgeInsets(top: margin, left:margin, bottom: 0, right: margin)
        super.init(collectionViewLayout: layout)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.registerClass(HMPictureCell.self, forCellWithReuseIdentifier: pictureCellID)
    }

}
extension HMPicturePickerController{
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return images.count + 1 <= maxImageCount ? images.count + 1 : colCountKey
    }
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! HMPictureCell
        cell.backgroundColor = UIColor.yellowColor()
        cell.delegate = self
        if images.count != indexPath.item {
            cell.image = images[indexPath.item]
        }else{
            cell.image = nil
        }
        return cell
    }
}

extension HMPicturePickerController: HMPictureCellDelegate{
    func userWillAddPicture(cell: HMPictureCell) {
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum){
            print("没有访问权限")
            return
        }
        let picker_hm = HMImagePickerController(selectedAssets: imagesAsset)
        picker_hm.pickerDelegate = self
        picker_hm.maxPickerCount = maxImageCount
        picker_hm.targetSize = CGSize(width: 200, height: 200)
        presentViewController(picker_hm, animated: true, completion: nil)
        /*
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum){
            print("没有访问权限")
            return
        }
        let picker_system = UIImagePickerController()
        picker_system.delegate = self
        picker_system.allowsEditing = true
        presentViewController(picker_system, animated: true, completion: nil)
        */
    }
    func userWillDeletePicture(cell: HMPictureCell) {
        /*
        guard let indexPath = collectionView?.indexPathForCell(cell) else{
            return
        }
        images.removeAtIndex(indexPath.item)
        collectionView?.reloadData()
         */
        guard let indexPath = collectionView?.indexPathForCell(cell) else{
            return
        }
        images.removeAtIndex(indexPath.item)
        imagesAsset.removeAtIndex(indexPath.item)
        collectionView?.reloadData()
    }
}
/*
extension HMPicturePickerController: UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    
       images.append(image)
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}
 */
extension HMPicturePickerController: HMImagePickerControllerDelegate{
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?){
        self.images = images
        guard let asset = selectedAssets else{
            return
        }
        self.imagesAsset = asset
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}
@objc protocol HMPictureCellDelegate: NSObjectProtocol{
    optional func userWillAddPicture(cell: HMPictureCell)
    optional func userWillDeletePicture(cell: HMPictureCell)
}
class HMPictureCell: UICollectionViewCell {
    weak var delegate: HMPictureCellDelegate?
    var image: UIImage?{
        didSet{
            deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    private func setupUI(){
        contentView.addSubview(addBtn)
        addBtn.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        contentView.addSubview(imageV)
        imageV.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        imageV.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        contentView.addSubview(deleteBtn)
        deleteBtn.snp_makeConstraints { (make) in
            make.top.right.equalTo(contentView)
        }
    }
    lazy var addBtn: UIButton = {
        let btn = UIButton()
        let imageName = "compose_pic_add"
        let image = UIImage(named: imageName)
        let image_high = UIImage(named: imageName + "_highlighted")
        btn.setBackgroundImage(image, forState: .Normal)
        btn.setBackgroundImage(image_high, forState: .Highlighted)
        btn.addTarget(self, action: #selector(HMPictureCell.addBtnClick(_:)), forControlEvents: .TouchUpInside)
        return btn
    }()
    lazy var deleteBtn: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named:"compose_photo_close"), forState: .Normal)
        btn.sizeToFit()
        btn.addTarget(self, action: #selector(deleteBtnClick), forControlEvents: .TouchUpInside)
        return btn
    }()
    @objc private func addBtnClick(btn: UIButton){
        if image != nil {
            print("已经设置过图片了")
            return
        }
        delegate?.userWillAddPicture?(self)
    }
    @objc private func deleteBtnClick(){
        delegate?.userWillDeletePicture?(self)
    }
    
    private lazy var imageV: UIImageView = {
        let iv = UIImageView()
        iv.contentMode = .ScaleAspectFill
        iv.clipsToBounds = true
        return iv
    }()
}
